package controlador;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import modelo.bd.excepcion.DAOException;
import modelo.dominio.Proveedor;
import modelo.servicio.Proveedores;

public class ProveedorControlador extends HttpServlet {

    private String accion;
    private String usuario;
    private StringBuilder html;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        html = new StringBuilder("");
        accion = request.getParameter("ac") != null
                ? request.getParameter("ac") : "";
        usuario = request.getSession().getAttribute("sUsuario") != null
                ? request.getSession().getAttribute("sUsuario").toString() : "";
        try {
            if (accion.compareToIgnoreCase("ls") == 0) {
            } else if (accion.compareToIgnoreCase("op") == 0) {
                List<Proveedor> proveedores = Proveedores.instancia().todos();
//                out.println(generarOpcionesUsuario(proveedores));
            }
            out.println(html);
        } catch (DAOException dex) {
            out.println("Error en la base de datos: " + dex.getMessage() + "<br/>" + dex.getLocalizedMessage());
        } finally {
            out.close();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    private void generarOpcionesUsuario(List<Proveedor> proveedores) {
        html.append("<select name='cmb_proveedor").append("'>");
        for (Proveedor proveedor : proveedores) {
            html.append("<option value='").append(proveedor.getIdentificador()).append("'>");
            html.append(proveedor.getIdentificador()).append(" - ");
            if (proveedor.getRazonSocial().length() > 30) {
                html.append(proveedor.getRazonSocial().substring(0, 30));
            } else {
                html.append(proveedor.getRazonSocial());
            }
            html.append("</option>");
        }
        html.append("</select>");
    }
}
